//
//  ASAddMyHonorVC.m
//  AttendenceSys
//
//  Created by 窦芳俊 on 16/4/13.
//  Copyright © 2016年 窦芳俊. All rights reserved.
//

#import "ASAddMyHonorVC.h"
#import "FTPhotoAlbumController.h"
#import "FTAlbumPhotosController.h"

@interface ASAddMyHonorVC ()

@end

@implementation ASAddMyHonorVC

- (instancetype)initWithTypeId:(NSInteger)typeId
{
    self = [super init];
    if (self)
    {
        _typeID = typeId;
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _releaseArrImage = [[NSMutableArray alloc] init];
    
    self.strNavTitle = @"增加奖惩";
    [self setRightText:@"保存"];
    
    [self initUI];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)initUI
{
    CGFloat padding = 10.0f;
    
    // 奖励名称
    _honorName = [[UILabel alloc] initWithFrame:CGRectMake(padding, 20, 70, 20)];
    _honorName.font = [UIFont systemFontOfSize:16];
    _honorName.text = @"奖励名称:";
    [_honorName setTextAlignment:NSTextAlignmentLeft];
    _honorName.textColor = [UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0];
    [self.view addSubview:_honorName];
    
    _inputHonorName = [[UITextField alloc] initWithFrame:CGRectMake(_honorName.frame.origin.x + _honorName.frame.size.width + 5,
                                                               _honorName.frame.origin.y,
                                                               self.view.frame.size.width - 80 - 10,
                                                               20)];
    _inputHonorName.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inputHonorName.textColor = [UIColor blackColor];
    _inputHonorName.returnKeyType = UIReturnKeyDone;
    _inputHonorName.placeholder = @"输入奖励名称";
    [_inputHonorName setBackgroundColor:[UIColor clearColor]];
    _inputHonorName.delegate = self;
    _inputHonorName.font = [UIFont systemFontOfSize:16.0f];
    _inputHonorName.borderStyle = UITextBorderStyleNone;
    [self.view addSubview:_inputHonorName];
    
    // 奖励单位
    _honorDepart = [[UILabel alloc] initWithFrame:CGRectZero];
    _honorDepart.frame = CGRectMake(padding, _honorName.frame.origin.y + _honorName.frame.size.height + 18, 70, 20);
    _honorDepart.font = [UIFont systemFontOfSize:16];
    _honorDepart.text = @"奖励单位:";
    [_honorDepart setTextAlignment:NSTextAlignmentLeft];
    _honorDepart.textColor = [UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0];
    [self.view addSubview:_honorDepart];
    
    _inputHonorDepart = [[UITextField alloc] initWithFrame:CGRectMake(_honorDepart.frame.origin.x + _honorDepart.frame.size.width + 5,
                                                                    _honorDepart.frame.origin.y,
                                                                    self.view.frame.size.width - 80 - 10,
                                                                    20)];
    _inputHonorDepart.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inputHonorDepart.textColor = [UIColor blackColor];
    _inputHonorDepart.returnKeyType = UIReturnKeyDone;
    _inputHonorDepart.placeholder = @"输入奖励单位";
    [_inputHonorDepart setBackgroundColor:[UIColor clearColor]];
    _inputHonorDepart.delegate = self;
    _inputHonorDepart.font = [UIFont systemFontOfSize:16.0f];
    _inputHonorDepart.borderStyle = UITextBorderStyleNone;
    [self.view addSubview:_inputHonorDepart];
    
    // 奖励级别
    _honorLevel = [[UILabel alloc] initWithFrame:CGRectZero];
    _honorLevel.frame = CGRectMake(padding, _honorDepart.frame.origin.y + _honorDepart.frame.size.height + 18, 70, 20);
    _honorLevel.font = [UIFont systemFontOfSize:16];
    _honorLevel.text = @"奖励级别:";
    [_honorLevel setTextAlignment:NSTextAlignmentLeft];
    _honorLevel.textColor = [UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0];
    [self.view addSubview:_honorLevel];
    
    _inputHonorLevel = [[UITextField alloc] initWithFrame:CGRectMake(_honorLevel.frame.origin.x + _honorLevel.frame.size.width + 5,
                                                                      _honorLevel.frame.origin.y,
                                                                      self.view.frame.size.width - 80 - 10,
                                                                      20)];
    _inputHonorLevel.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inputHonorLevel.textColor = [UIColor blackColor];
    _inputHonorLevel.returnKeyType = UIReturnKeyDone;
    _inputHonorLevel.placeholder = @"输入奖励级别";
    [_inputHonorLevel setBackgroundColor:[UIColor clearColor]];
    _inputHonorLevel.delegate = self;
    _inputHonorLevel.font = [UIFont systemFontOfSize:16.0f];
    _inputHonorLevel.borderStyle = UITextBorderStyleNone;
    [self.view addSubview:_inputHonorLevel];
    
    // 奖励时间
    _honorTime = [[UILabel alloc] initWithFrame:CGRectZero];
    _honorTime.frame = CGRectMake(padding, _honorLevel.frame.origin.y + _honorLevel.frame.size.height + 18, 70, 20);
    _honorTime.font = [UIFont systemFontOfSize:16];
    _honorTime.text = @"奖励时间:";
    [_honorTime setTextAlignment:NSTextAlignmentLeft];
    _honorTime.textColor = [UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0];
    [self.view addSubview:_honorTime];

    _inputHonorTime = [[UITextField alloc] initWithFrame:CGRectMake(_honorTime.frame.origin.x + _honorTime.frame.size.width + 5,
                                                                     _honorTime.frame.origin.y,
                                                                     self.view.frame.size.width - 80 - 10,
                                                                     20)];
    _inputHonorTime.clearButtonMode = UITextFieldViewModeWhileEditing;
    _inputHonorTime.textColor = [UIColor blackColor];
    _inputHonorTime.returnKeyType = UIReturnKeyDone;
    _inputHonorTime.placeholder = @"输入奖励时间";
    [_inputHonorTime setBackgroundColor:[UIColor clearColor]];
    _inputHonorTime.delegate = self;
    _inputHonorTime.font = [UIFont systemFontOfSize:16.0f];
    _inputHonorTime.borderStyle = UITextBorderStyleNone;
    [self.view addSubview:_inputHonorTime];
    
    // 奖惩描述
    _inputHonorDesc = [[UITextView alloc] initWithFrame:CGRectMake(5,
                                                                   _honorTime.frame.origin.y + _honorTime.frame.size.height + 15,
                                                                   [UIScreen mainScreen].bounds.size.width - 20,
                                                                   200)];
    _inputHonorDesc.delegate = self;
    _inputHonorDesc.hidden = NO;
    _inputHonorDesc.textColor = [UIColor blackColor];
    _inputHonorDesc.textAlignment = NSTextAlignmentLeft;
    _inputHonorDesc.backgroundColor =  [UIColor clearColor];
    _inputHonorDesc.font = [UIFont systemFontOfSize:16.0];
    _inputHonorDesc.layer.cornerRadius = 3;
    _inputHonorDesc.autocorrectionType = UITextAutocorrectionTypeNo;
    
    _honorDesc = [[UILabel alloc] initWithFrame:CGRectMake(5, 7, _inputHonorDesc.frame.size.width, 20)];
    _honorDesc.enabled = NO;
    _honorDesc.backgroundColor = [UIColor clearColor];
    _honorDesc.text = @"请输入奖惩描述...";
    _honorDesc.font = [UIFont systemFontOfSize:16.0];
    _honorDesc.textColor = [UIColor colorWithRed:134/255.0 green:139/255.0 blue:142/255.0 alpha:1];
    [_inputHonorDesc addSubview:_honorDesc];
    [self.view addSubview:_inputHonorDesc];
    
    [self initScrollView:_releaseArrImage];
}

// 删除背景视图
- (void)removeBackView
{
    if (_backgroundView)
    {
        [_backgroundView removeFromSuperview];
        _backgroundView = nil;
    }
}

- (UIView*)topView
{
    UIViewController *recentView = self;
    
    while (recentView.parentViewController != nil)
    {
        recentView = recentView.parentViewController;
    }
    
    return recentView.view;
}

- (void)initScrollView:(NSMutableArray*)arrImage
{
    if (_imageScrollView)
    {
        [_imageScrollView removeFromSuperview];
    }
    
    _imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    _imageScrollView.frame = CGRectMake(0,
                                        _inputHonorDesc.frame.origin.y + _inputHonorDesc.frame.size.height + 10,
                                        [UIScreen mainScreen].bounds.size.width,
                                        70);
    _imageScrollView.directionalLockEnabled = YES; //只能一个方向滑动
    _imageScrollView.pagingEnabled = YES; //是否翻页
    _imageScrollView.backgroundColor = [UIColor clearColor];
    _imageScrollView.showsVerticalScrollIndicator = NO; //垂直方向的滚动指示
    _imageScrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;//滚动指示的风格
    _imageScrollView.showsHorizontalScrollIndicator = YES;//水平方向的滚动指示
    _imageScrollView.userInteractionEnabled = YES;
    _imageScrollView.delegate = self;
    [self.view addSubview:_imageScrollView];
    
    //设置滚动视图的位置
    [_imageScrollView setContentSize:CGSizeMake(([UIScreen mainScreen].bounds.size.width/5*(arrImage.count+1)),
                                                _imageScrollView.frame.size.height)];
    
    for (int i = 0; i < arrImage.count; i++)
    {
        NSData* data = [arrImage objectAtIndex:i];
        UIButton* imageBtnView = [[UIButton alloc] initWithFrame:CGRectMake(10*(i+1) + i*([UIScreen mainScreen].bounds.size.width-60)/5,
                                                                            0,
                                                                            ([UIScreen mainScreen].bounds.size.width-60)/5,
                                                                            ([UIScreen mainScreen].bounds.size.width-60)/5)];
        [imageBtnView setBackgroundColor:[UIColor redColor]];
        imageBtnView.contentMode = UIViewContentModeScaleAspectFill;
        //UIViewContentModeScaleAspectFit
        UIImage* image = [UIImage imageWithData:data];
        [imageBtnView setBackgroundImage:image forState:UIControlStateNormal];
        [_imageScrollView addSubview:imageBtnView];
    }
    
    NSInteger count = arrImage.count;
    UIButton* addBtn = [[UIButton alloc] initWithFrame:CGRectMake(10*(count+1) + count*([UIScreen mainScreen].bounds.size.width-60)/5,
                                                                  0,
                                                                  ([UIScreen mainScreen].bounds.size.width-60)/5,
                                                                  ([UIScreen mainScreen].bounds.size.width-60)/5)];
    addBtn.backgroundColor = [UIColor clearColor];
    [addBtn setBackgroundImage:[UIImage imageNamed:@"ic_add"] forState:UIControlStateNormal];
    [_imageScrollView addSubview:addBtn];
    [addBtn addTarget:self action:@selector(addImage) forControlEvents:UIControlEventTouchUpInside];
    [_imageScrollView addSubview:addBtn];
}

- (void)addImage
{
    FTPhotoAlbumController* phoAlbum = [[FTPhotoAlbumController alloc] init];
    phoAlbum.albumDelegate = self;
    phoAlbum.videoDelegate = self;
    phoAlbum.albumType = AlbumType_MutiForSending;
    ASBaseNavigationController* baseNavi = [[ASBaseNavigationController alloc] initWithRootViewController:phoAlbum];
    [self presentViewController:baseNavi animated:YES completion:nil];
}

- (void)selectHonorLevel:(NSString *)level
{
    _inputHonorLevel.text = level;
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonPressed:(id)action
{
    [self uploadSelectImages];
    //[self uploadHonorInfo];
}

// 上传选择的图片
- (void)uploadSelectImages
{
    // 上传图片接口 http://211.65.216.54/uploadAction.do?type=1&userCode=xiaohu
    // type=1 上传头像  2表示请假  3表示 发布成长   其他表示发布活动
    
    NSString* refer = @"uploadAction.do?type=3&userCode=";
    NSString* prefix = kASHttpUrl(refer);
    NSString* userCode = [ASAppDelegate sharedAppDelegate].userInfo.userCode;
    NSString* totalUrl = [prefix stringByAppendingString:userCode];
    
    // 提交信息上传
    NSString* achiTitle = _inputHonorName.text;    //名称
    NSString* achiDepart = _inputHonorDepart.text; //单位
    NSString* achiLevel = _inputHonorLevel.text;   //级别
    NSString* achiTime = _inputHonorTime.text;     //时间
    NSString* achiDesc = _inputHonorDesc.text;     //奖惩描述
    NSString* infoUrl = [NSString stringWithFormat:@"&conditonTitle=%@&condtionTypeId=%ld&conditionUnit=%@&conditionLevel=%@&conditionDate=%@&conditionDesc=%@",
                          achiTitle,
                          (long)_typeID,
                          achiDepart,
                          achiLevel,
                          achiTime,
                          achiDesc];
    totalUrl = [totalUrl stringByAppendingString:infoUrl];
    
    [SVProgressHUD showWithStatus:@"上传图片..." maskType:SVProgressHUDMaskTypeClear];
    
    typeof(self) __weak weakSelf = self;
    ASNetworkEngine *netEngine = [ASNetworkEngine sharedInstance];
    [netEngine uploadImagesWithUrl:totalUrl image:_releaseArrImage progressBlock:^(long long bytesRead, long long totalBytes) {
        
    } completionBlock:^(id responseObject) {
        
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            [SVProgressHUD showSuccessWithStatus:@"新增成功"];
            [weakSelf popToListVC];
        }
        
    } failure:^(NSString *errorMsg) {
        
        [SVProgressHUD showErrorWithStatus:errorMsg.description];
    }];
}

- (void)uploadHonorInfo
{
    //发布用户状况的接口 http://211.65.216.54/addUserCondition.action?userCode=xiaohu&conditionDesc=asdasdasdasd&condtionTypeId=1&researchSubjectId=1&researchRemark=111&researchDesc=2222&researchSubjectId=1&conditionArea=111 condtionTypeId -1表示全部，1专业实习，2志愿服务，3社会实践，4其他 5奖惩 6科研 奖惩的时候 conditionUnit奖励单位 conditionLevel奖励级别字段 researchSubjectId科研类别researchRemark科研备注researchDesc可研描述conditionArea地点 conditionDesc状况的描述 2000汉字以内
    
    NSString* refer = @"addUserCondition.action?";
    NSString* prefix = kASHttpUrl(refer);
    NSString* userCode = [ASAppDelegate sharedAppDelegate].userInfo.userCode;
    NSString* achiTitle = _inputHonorName.text; //名称
    NSString* achiDepart = _inputHonorDepart.text; //单位
    NSString* achiLevel = _inputHonorLevel.text; //级别
    NSString* achiTime = _inputHonorTime.text; //时间
    
    NSString* totalUrl = [NSString stringWithFormat:@"%@userCode=%@&conditonTitle=%@&condtionTypeId=%ld&conditionUnit=%@&conditionLevel=%@&conditionDate=%@",
                          prefix,
                          userCode,
                          achiTitle,
                          (long)_typeID,
                          achiDepart,
                          achiLevel,
                          achiTime];
    
    typeof(self) __weak weakSelf = self;
    [SVProgressHUD showWithStatus:@"提交中..." maskType:SVProgressHUDMaskTypeClear];
    ASNetworkEngine *networkingEngine = [ASNetworkEngine sharedInstance];
    [networkingEngine GET:totalUrl parameters:nil success:^(id responseObject) {
        NSDictionary* jsonRsp = (NSDictionary *)responseObject;
        if (isSuccessRsp(jsonRsp))
        {
            NSString* retMsg = [jsonRsp objectForKey:kASJsonMsgData];
            
            if ([retMsg isEqualToString:@"新增成功"])
            {
                [SVProgressHUD showSuccessWithStatus:retMsg];
                
                [weakSelf popToListVC];
            }
            else
            {
                [SVProgressHUD dismiss];
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:errorMsgRsp(jsonRsp)];
        }
    } failure:^(NSError *error) {
        //[SVProgressHUD showErrorWithStatus:error.description];
        [SVProgressHUD showErrorWithStatus:@"网络异常，请稍后再试"];
    }];
}

- (void)popToListVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - FTAlbumPhotoViewControllerDelegate

- (void)albumDidFinishPickingWithInfo:(NSMutableArray *)info
                          IsOriginImg:(BOOL)isOriginImg
                        withAlbumType:(AlbumType)albumType
{
    _releaseArrImage = info;
    [self initScrollView:_releaseArrImage];
    
    NSInteger offsetCount = 0;
    if (4 <_releaseArrImage.count)
    {
        offsetCount = _releaseArrImage.count-4;
        [_imageScrollView setContentOffset:CGPointMake(10*offsetCount + offsetCount*([UIScreen mainScreen].bounds.size.width-60)/5, 0)];
    }
}

#pragma mark - RCSVideoPickerDelegate
- (void)selectedVideoDictionary:(NSDictionary *)videoDic
                 pickController:(UIViewController *)ctr
                      videoData:(NSMutableArray*)videoData
{
}

#pragma mark - ASDatePickerViewDelegate

- (void)datePickerCancel
{
    [self removeBackView];
}

- (void)dataPickSelect:(NSInteger)selectTag selectDate:(NSString*)selectData
{
    NSString *strDate = selectData;
    NSRange range = [strDate rangeOfString:@" "];
    if (range.length > 0)
    {
        strDate = [strDate substringToIndex:range.location];
    }
    
    _inputHonorTime.text = strDate;
    
    [self removeBackView];
}

- (void)initDatePickerView
{
    _dateSelctPickerView = [[ASDatePickerView alloc] initWithFrame:CGRectMake(0,
                                                                              self.view.frame.size.height- 216 - 46,
                                                                              [UIScreen mainScreen].bounds.size.width,
                                                                              216 + 46)];
    _dateSelctPickerView.iTag = 0;
    _dateSelctPickerView.editTimeLab.text = @"选择日期";
    _dateSelctPickerView.delegate = self;
    _dateSelctPickerView.datePickerView.datePickerMode =UIDatePickerModeDate;
    NSDate* minDate = [NSDate date];
    _dateSelctPickerView.datePickerView.minimumDate = minDate;
    
    [self.view addSubview:_dateSelctPickerView];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [textField resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (_inputHonorTime == textField)
    {
        UIView* sourceView = [self topView];
        _backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                                   0,
                                                                   sourceView.frame.size.width,
                                                                   sourceView.frame.size.height - 216 - 46)];
        [_backgroundView setBackgroundColor:[UIColor blackColor]];
        _backgroundView.alpha = 0.5;
        [sourceView addSubview:_backgroundView];
        [self initDatePickerView];
        
        return NO;
    }
    
    if (_inputHonorLevel == textField)
    {
        ASHonorLevelVC *honorLevelVC = [[ASHonorLevelVC alloc] init];
        honorLevelVC.hidesBottomBarWhenPushed = YES;
        honorLevelVC.delegate = self;
        [self.navigationController pushViewController:honorLevelVC animated:YES];
        
        return NO;
    }
    
    return YES;
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length == 0)
    {
        if (textView == _inputHonorDesc)
        {
            _honorDesc.text = @"请输入奖惩描述...";
        }
    }
    else
    {
        if (textView == _inputHonorDesc)
        {
            _honorDesc.text = @"";
        }
    }
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    return YES;
}




@end




